package com.darren.euc.dao.impl;

import java.math.BigInteger;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.jdbc.Work;
import org.springframework.stereotype.Repository;

import com.darren.euc.dao.MemberDao;
import com.darren.euc.entity.Member;
import com.darren.euc.entity.PageBean;

/**
 * Created by Machenike-Pc on 2018/3/11.
 */
@Repository
public class MemberDaoImpl extends BaseDaoImpl<Member,Integer> implements MemberDao {
    @Override
    public Member findByMobile(String mobile) {
        PageBean pageBean = queryForPageBySQL("select * from euc_member where mobile=?", 1, 1, mobile);

        List<Member> list = pageBean.getList();
        return list.size() == 0 ? null : list.get(0);
    }
    
    @Override
    public Member findByIcCard(String icCard){    	
    	Session session = sessionFactory.getCurrentSession();	
		Query query = session.createSQLQuery("select * from euc_member where employ_status = 1 and ic_card like ? and char_length(?) = 8 ; ").addEntity(Member.class);
		query.setParameter(0, "%"+icCard+"%");
		query.setParameter(1, icCard);
        return (Member) query.uniqueResult();
    }

    @Override
    public Member findByToken(String token) {
        PageBean pageBean = queryForPageBySQL(
                "SELECT * FROM euc_member WHERE employ_status<4 and id=(SELECT member_id FROM euc_member_token WHERE token=?)",
                1, 1, token);

        List<Member> list = pageBean.getList();
        return list.size() == 0 ? null : list.get(0);
    }
    
    
    /**
     * 通过客户ID号码查询Member数
     * @param mobile
     * @return
     */
    @Override
    public BigInteger findByClientID(Integer clientId){
    	Session session = sessionFactory.getCurrentSession();	
		Query query = session.createSQLQuery("SELECT COUNT(1) from euc_member where client_id = ? and employ_status < 4 ");
		query.setParameter(0, clientId);
		BigInteger memberCount = (BigInteger) query.uniqueResult();
		return memberCount;
    }
    
    
    /**
	 * 更新Member 状态
	 */
    @Override
	public void updateMemberStatus(){
    	Session session = sessionFactory.getCurrentSession();	
		session.doWork(new Work() {			
			@Override
			public void execute(Connection connection) throws SQLException {
				// TODO Auto-generated method stub
				CallableStatement  callableStatement = connection.prepareCall("{call usp_update_member_status}");
				callableStatement.execute();
			}
		});
    }
}
